package com.nengchuan.kbms.dfs.util.pdf;

import com.itextpdf.text.*;
import com.itextpdf.text.pdf.*;
import com.nengchuan.config.exception.NcException;
import com.nengchuan.kbms.dfs.entity.dto.DownloadFileDTO;
import org.apache.commons.lang3.StringUtils;

import javax.swing.*;
import java.io.*;

/**
 * Description: 审核意见生成pdf工具类 <br>
 *
 * @author luo_zm
 */
public class ItextPdfUtil {

    /**
     * @param InPdfFile     要加水印的原pdf文件路径
     * @param outPdfFile    加了水印后要输出的路径
     * @param markImagePath 水印图片路径
     * @param imgWidth      图片横坐标
     * @param imgHeight     图片纵坐标
     * @throws Exception
     */
    public static void addPdfImgMark(String InPdfFile, String outPdfFile, String markImagePath, int imgWidth,
                                     int imgHeight) throws Exception {
        PdfReader reader = new PdfReader(InPdfFile, "PDF".getBytes());
        PdfStamper stamp = new PdfStamper(reader, new FileOutputStream(new File(outPdfFile)));

        PdfContentByte under;

        PdfGState gs1 = new PdfGState();
        gs1.setFillOpacity(0.3f);// 透明度设置

        Image img = Image.getInstance(markImagePath);// 插入图片水印

        img.setAbsolutePosition(imgWidth, imgHeight); // 坐标
        img.setRotation(0);// 旋转 弧度
        img.setRotationDegrees(45);// 旋转 角度
        img.scaleAbsolute(100, 80);// 自定义大小
        // img.scalePercent(50);//依照比例缩放

        int pageSize = reader.getNumberOfPages();// 原pdf文件的总页数
        for (int i = 1; i <= pageSize; i++) {
            under = stamp.getUnderContent(i);// 水印在之前文本下
            // under = stamp.getOverContent(i);//水印在之前文本上
            under.setGState(gs1);// 图片水印 透明度
            under.addImage(img);// 图片水印
        }

        stamp.close();// 关闭
        reader.close();
    }

    public static void addPdfImgMark(String InPdfFile, String outPdfFile, String markImagePath) throws Exception {
        PdfReader reader = new PdfReader(InPdfFile, "PDF".getBytes());
        PdfStamper stamp = new PdfStamper(reader, new FileOutputStream(new File(outPdfFile)));

        PdfContentByte under;
        // 透明度设置
        PdfGState gs1 = new PdfGState();
        gs1.setFillOpacity(0.2f);
        // 插入图片水印
        Image img = Image.getInstance(markImagePath);
        // 坐标
        img.setAbsolutePosition(180, 360);
        // 旋转 弧度
        img.setRotation(0);
        // 旋转 角度
        img.setRotationDegrees(45);
        // 自定义大小
        img.scaleAbsolute(240, 80);
        // img.scalePercent(50);//依照比例缩放
        // 原pdf文件的总页数
        int pageSize = reader.getNumberOfPages();
        for (int i = 1; i <= pageSize; i++) {
            // 水印在之前文本下
            under = stamp.getUnderContent(i);
            // under = stamp.getOverContent(i);//水印在之前文本上
            // 图片水印 透明度
            under.setGState(gs1);
            // 图片水印
            under.addImage(img);
        }

        stamp.close();// 关闭
        reader.close();
    }

    /**
     * 功能描述: 添加文字水印-多个
     *
     * @Param: [pdfIn, outPdfFile, textMark, ownerPass]
     * @Return: void
     * @Author: luo_zm
     * @Date: 2020/4/9 10:29
     */
    public static void addLostWater(byte[] pdfIn, String outPdfFile, DownloadFileDTO downloadFileDTO) {
        if (StringUtils.isEmpty(downloadFileDTO.getWaterText())) {
            addWaterWithOutText(pdfIn, outPdfFile, downloadFileDTO);
        } else {
            addWaterWithText(pdfIn, outPdfFile, downloadFileDTO);
        }
    }

    private static void addWaterWithText(byte[] pdfIn, String outPdfFile, DownloadFileDTO downloadFileDTO) {
        PdfReader reader = null;
        PdfStamper stamper = null;
        try {
            reader = new PdfReader(pdfIn);
            stamper = new PdfStamper(reader, new FileOutputStream(new File(outPdfFile)));

            //BaseFont font = BaseFont.createFont("C:/WINDOWS/Fonts/SIMSUN.TTC,1", "Identity-H", true);// 使用系统字体
            BaseFont font = BaseFont.createFont("STSong-Light", "UniGB-UCS2-H", BaseFont.EMBEDDED);

            PdfGState gs = new PdfGState();
            // 设置透明度为
            gs.setFillOpacity(0.1f);
            gs.setStrokeOpacity(0.1f);
            int total = reader.getNumberOfPages() + 1;

            JLabel label = new JLabel();
            label.setText(downloadFileDTO.getWaterText());
            PdfContentByte under;
            Rectangle pageRect = null;
            for (int i = 1; i < total; i++) {
                pageRect = reader.getPageSizeWithRotation(i);
                under = stamper.getOverContent(i);
                under.saveState();
                under.setGState(gs);
                under.beginText();
                under.setFontAndSize(font, 38);

                for (int x = 0; x < 5; x++) {
                    for (int j = 0; j < 5; j++) {
                        under.showTextAligned(Element.ALIGN_LEFT, downloadFileDTO.getWaterText(),
                                (50.5f + x * 350),
                                (40.0f + j * 150),
                                i % 2 == 1 ? 45 : -45);
                    }
                }
                //权限设置
                PdfWriter pdfWriter = under.getPdfWriter();
                judgeEmptyProperty(downloadFileDTO, pdfWriter);

                under.endText();
            }
        } catch (IOException e) {
            e.printStackTrace();
        } catch (DocumentException e) {
            throw new NcException("生成水印pdf失败");
        } finally {
            //一定不要忘记关闭流
            try {
                stamper.close();//关闭
            } catch (DocumentException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }
            reader.close();
        }
    }

    /**
     * 功能描述: 添加文字水印-单个
     *
     * @Param: [pdfIn, outPdfFile, textMark, ownerPass]
     * @Return: void
     * @Author: luo_zm
     * @Date: 2020/4/9 10:29
     */
    public static void addPdfTextMarkOne(byte[] pdfIn, String outPdfFile, DownloadFileDTO downloadFileDTO) throws Exception {
        if (StringUtils.isEmpty(downloadFileDTO.getWaterText())) {
            addWaterWithOutText(pdfIn, outPdfFile, downloadFileDTO);
        } else {
            addOneWater(pdfIn, outPdfFile, downloadFileDTO);
        }
    }

    private static void addOneWater(byte[] pdfIn, String outPdfFile, DownloadFileDTO downloadFileDTO) throws IOException, DocumentException {
        PdfReader reader = new PdfReader(pdfIn);
        PdfStamper stamp = new PdfStamper(reader, new FileOutputStream(new File(outPdfFile)));

        PdfContentByte under;
        // 设置透明度为
        PdfGState gs = new PdfGState();
        gs.setFillOpacity(0.1f);
        gs.setStrokeOpacity(0.1f);
//        BaseFont font = BaseFont.createFont("C:/WINDOWS/Fonts/SIMSUN.TTC,1", "Identity-H", true);// 使用系统字体
//        BaseFont font = BaseFont.createFont("/fonts/Alibaba-PuHuiTi-Regular.otf", "utf-8", BaseFont.EMBEDDED);
        BaseFont font = BaseFont.createFont("STSong-Light", "UniGB-UCS2-H", BaseFont.EMBEDDED);
        // 原pdf文件的总页数

        int pageSize = reader.getNumberOfPages();
        for (int i = 1; i <= pageSize; i++) {
            // 水印在之前文本下
            under = stamp.getUnderContent(i);
            //水印在之前文本上
            // under = stamp.getOverContent(i);
            under.setGState(gs);
            under.saveState();
            under.beginText();
            // 文字水印 颜色
            under.setColorFill(new BaseColor(211, 211, 211));
            // 文字水印 字体及字号
            under.setFontAndSize(font, 64);
            // 文字水印 起始位置
            //under.setTextMatrix(300, 400);
            under.showTextAligned(Element.ALIGN_CENTER, downloadFileDTO.getWaterText(), 600, 400, 45);
            PdfWriter pdfWriter = under.getPdfWriter();
            // 水印
            judgeEmptyProperty(downloadFileDTO, pdfWriter);

            under.endText();
        }
        stamp.close();// 关闭
        reader.close();
    }

    /**
     * 功能描述:生成没有水印的pdf
     *
     * @Param: [pdfIn, outPdfFile, ownerPass]
     * @Return: void
     * @Author: luo_zm
     * @Date: 2020/4/13 14:20
     */
    public static void addWaterWithOutText(byte[] pdfIn, String outPdfFile, DownloadFileDTO downloadFileDTO) {
        PdfReader reader = null;
        PdfStamper stamp = null;
        try {
            reader = new PdfReader(pdfIn);
            stamp = new PdfStamper(reader, new FileOutputStream(new File(outPdfFile)));
            PdfContentByte under;
            BaseFont font = BaseFont.createFont("STSong-Light", "UniGB-UCS2-H", BaseFont.EMBEDDED);
            // 原pdf文件的总页数
            int pageSize = reader.getNumberOfPages();
            for (int i = 1; i <= pageSize; i++) {
                // 水印在之前文本下
                under = stamp.getUnderContent(i);
                PdfWriter pdfWriter = under.getPdfWriter();
                judgeEmptyProperty(downloadFileDTO, pdfWriter);

            }
        } catch (IOException e) {
            e.printStackTrace();
        } catch (DocumentException e) {
            throw new NcException("生成没有水印的pdf");
        } finally {
            try {
                stamp.close();//关闭
            } catch (DocumentException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }
            reader.close();
        }
    }

    /**
     * 功能描述: 判断密码是否为空,设置对应的权限
     *
     * @Param: [downloadFileDTO, pdfWriter]
     * @Return: void
     * @Author: luo_zm
     * @Date: 2020/4/13 16:05
     */
    private static void judgeEmptyProperty(DownloadFileDTO downloadFileDTO, PdfWriter pdfWriter) throws DocumentException {
        String visitPassWord = downloadFileDTO.getVisitPassWord();
        String ownerPassWord = downloadFileDTO.getOwnerPassWord();

        if (StringUtils.isEmpty(visitPassWord) && StringUtils.isEmpty(ownerPassWord)) {

        } else if (!StringUtils.isEmpty(visitPassWord) && StringUtils.isEmpty(ownerPassWord)) {
            //不能单独设置访问者密码,不然pdfWriter会用this.md5.digest(createDocumentId())来作为编辑密码,这里我们使用默认的123456
            pdfWriter.setEncryption(visitPassWord.getBytes(), "123456".getBytes(),
                    PdfWriter.ALLOW_COPY, PdfWriter.ENCRYPTION_AES_128);
        } else if (StringUtils.isEmpty(visitPassWord) && !StringUtils.isEmpty(ownerPassWord)) {
            pdfWriter.setEncryption(null, ownerPassWord.getBytes(),
                    PdfWriter.ALLOW_COPY, PdfWriter.ENCRYPTION_AES_128);
        } else if (!StringUtils.isEmpty(visitPassWord) && !StringUtils.isEmpty(ownerPassWord)) {
            pdfWriter.setEncryption(visitPassWord.getBytes(), ownerPassWord.getBytes(),
                    PdfWriter.ALLOW_COPY, PdfWriter.ENCRYPTION_AES_128);
        }
    }

    public static byte[] getByteFromFile(String filePath) throws Exception {
        File file = new File(filePath);
        //获取输入流
        FileInputStream fis = new FileInputStream(file);

        //新的 byte 数组输出流，缓冲区容量1024byte
        ByteArrayOutputStream bos = new ByteArrayOutputStream(1024);
        //缓存
        byte[] b = new byte[1024];
        int n;
        while ((n = fis.read(b)) != -1) {
            bos.write(b, 0, n);
        }
        fis.close();
        //改变为byte[]
        byte[] bytes = bos.toByteArray();
        bos.close();
        return bytes;
    }
}